﻿using AutoMapper;
using BMS.IService;
using BMS.IRepository;
using BMS.DTO;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BMS.Entity.RBAC;

namespace BMS.Service
{
    public class RoleService : BaseService<RoleInfo>, IRoleService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IRoleRepository roleRepository;
        private readonly IMapper mapper;
        private readonly IRolePermissionRepository rolePermissonRepository;
        private readonly IRoleUsersRepository roleuserRepository;
        private readonly IPermissionRepository permissionRepository;
        public RoleService(IUnitOfWork unitOfWork, IRoleRepository roleRepository, IMapper mapper, IRolePermissionRepository rolePermissionRepository, IRoleUsersRepository role_user, IPermissionRepository permissionRepository) : base(unitOfWork, roleRepository)
        {
            this.unitOfWork = unitOfWork;
            this.roleRepository = roleRepository;
            this.mapper = mapper;
            this.rolePermissonRepository = rolePermissionRepository;
            this.roleuserRepository = role_user;
            this.permissionRepository = permissionRepository;
        }

        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDTO<RoleReturnDTO>> RoleAdd(RoleAddRequestDTO dto)
        {
            //转换为RoleInfoInfo所需的格式
            var role = mapper.Map<RoleInfo>(dto);

            role.CreateTime = DateTime.Now;

            //判断该角色是否已经存在
            var IsExist = roleRepository.GetAll().Result.Where(m => m.Name == dto.Name).FirstOrDefault();
            if (IsExist != null)
            {
                return new ResultDTO<RoleReturnDTO>
                {
                    Data = null,
                    Code = Enum.ResultStatusCode.HANDLEFAIL,
                    Message = "该角色已经存在！！！"
                };
            }

            using (var tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //添加角色
                    await roleRepository.Insert(role);

                    //保存数据
                    await unitOfWork.SaveChanges();

                    //添加权限
                    List<RolePermissions> list = new List<RolePermissions>();

                    foreach (var item in dto.PermissionId)
                    {
                        list.Add(new RolePermissions
                        {
                            RoleId = role.Id,
                            PermissionId = item
                        });
                    }

                    //批量给新角色分配权限
                    await rolePermissonRepository.InsertBatch(list);

                    //提交数据
                    await unitOfWork.SaveChanges();

                    //提交事务
                    tran.Commit();

                    //返回值
                    return new ResultDTO<RoleReturnDTO>
                    {
                        Data = mapper.Map<RoleReturnDTO>(role),
                        Code = Enum.ResultStatusCode.SUCCESS,
                        Message = "添加成功！！！"
                    };
                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Rollback();

                    return new ResultDTO<RoleReturnDTO>
                    {
                        Data = null,
                        Code = Enum.ResultStatusCode.HANDLEFAIL,
                        Message = "操作失败！！！"
                    };
                }
            }


        }

        /// <summary> 
        /// 修改角色信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDTO<RoleReturnDTO>> RoleUpdate(RoleUpdateRequestDTO dto)
        {
            //var num = dto.PermissionId.Count();
            //var first = dto.PermissionId[0];

            //转换为RoleInfoInfo所需的格式
            var role = mapper.Map<RoleInfo>(dto);

            role.UpdateTime = DateTime.Now;

            //判断该角色是否已经存在
            var IsExist = (await roleRepository.GetAll()).AsNoTracking().Where(m => m.Id == dto.Id).FirstOrDefault();
            if (IsExist == null)
            {
                return new ResultDTO<RoleReturnDTO>
                {
                    Data = null,
                    Code = Enum.ResultStatusCode.HANDLEFAIL,
                    Message = "该角色不存在！！！"
                };
            }
            //开始事务
            using (var tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //修改角色信息
                    await roleRepository.Update(role);

                    //保存数据
                    await unitOfWork.SaveChanges();

                    //判断是否改变角色权限
                    //if (first != 0 && num != 0)
                    //{
                    //    //删除角色的所有旧权限
                    //    var delData = (await rolePermissonRepository.GetAll()).Where(m => m.RoleId == role.Id).ToList();

                    //    //删除原有权限
                    //    await rolePermissonRepository.DeleteBatch(delData);

                    //    //重新添加权限
                    //    List<RolePermissions> list = new List<RolePermissions>();

                    //    if (dto.PermissionId != null)
                    //    {
                    //        foreach (var item in dto.PermissionId)
                    //        {
                    //            list.Add(new RolePermissions
                    //            {
                    //                RoleId = role.Id,
                    //                PermissionId = item
                    //            });
                    //        }
                    //    }
                    //    //批量给新角色分配权限
                    //    await rolePermissonRepository.InsertBatch(list);
                    //    //提交数据
                    //    await unitOfWork.SaveChanges();
                    //}




                    //提交事务
                    tran.Commit();

                    //返回值
                    return new ResultDTO<RoleReturnDTO>
                    {
                        Data = mapper.Map<RoleReturnDTO>(role),
                        Code = Enum.ResultStatusCode.SUCCESS,
                        Message = "修改成功！！！"
                    };
                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Rollback();

                    return new ResultDTO<RoleReturnDTO>
                    {
                        Data = null,
                        Code = Enum.ResultStatusCode.HANDLEFAIL,
                        Message = "操作失败！！！"
                    };
                }
            }
        }

        /// <summary>
        /// 角色的分页显示+名称查询
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<ResultDTO<PageDTO<Role_PageDTO>>> RolePageShow(int pageSize, int pageIndex, string name)
        {

            var rolelist = from a in await roleRepository.GetAll()
                           where a.IsDeleted == false
                           select new Role_PageDTO
                           {
                               Id = a.Id,
                               Name = a.Name,
                               Roledescription = a.Roledescription,
                               Status = a.Status
                           };
            if (!string.IsNullOrEmpty(name))
            {
                rolelist = rolelist.Where(m => m.Roledescription.Contains(name));
            }
            return new ResultDTO<PageDTO<Role_PageDTO>>
            {
                Code = Enum.ResultStatusCode.SUCCESS,
                Message = "请求成功",
                Data = new PageDTO<Role_PageDTO>
                {
                    recordCount = rolelist.Count(),
                    plist = rolelist.OrderBy(a => a.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize)
                },

            };
        }

        /// <summary>
        /// 单个角色的详细显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDTO<RoleInfoDTO>> RoleSelectById(int id)
        {
            //角色权限关系表与权限表联查
            var rolepermission = from a in await rolePermissonRepository.GetAll()
                                 join b in await permissionRepository.GetAll() on a.PermissionId equals b.Id
                                 where a.IsDeleted == false && b.IsDeleted == false
                                 where a.RoleId == id
                                 select new
                                 {
                                     RoleId = a.RoleId,
                                     PermissionId = b.Id,
                                     PermissionName = b.Name
                                 };

            //角色表与 rolepermission 嵌套查询
            var roleInfo = from a in await roleRepository.GetAll()
                           where a.Id == id && a.IsDeleted == false
                           select new RoleInfoDTO
                           {
                               Id = a.Id,
                               Name = a.Name,
                               Roledescription = a.Roledescription,
                               PermissionList = rolepermission.Select(m => m.PermissionId).ToList(),
                           };

            //lowb wda 的方法查询
            //var data =await (await roleRepository.GetAll()).
            //    Where(m => m.Id == id).
            //    Select(m => new RoleInfoDTO
            //    {
            //        Id = m.Id,
            //        Name = m.Name,
            //        Roledescription = m.Roledescription,
            //        PermissionList= rolepermission.Where(x => x.RoleId == m.Id).Select(x => x.PermissionName).ToList()
            //    }).FirstOrDefaultAsync();


            return new ResultDTO<RoleInfoDTO>
            {
                Data = await roleInfo.FirstOrDefaultAsync(), //data
                Code = Enum.ResultStatusCode.SUCCESS,
                Message = "请求成功",
            };
        }

        /// <summary>
        /// 单个角色的真删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> RoleDel(RoleDelDTO dto)
        {
            //选择删除的角色
            var role = roleRepository.GetAll().Result.Where(m => m.Id == dto.Id).FirstOrDefault();

            //查询用户角色关系表中的角色信息
            var user_role = roleuserRepository.GetAll().Result.Where(m => m.RoleId == dto.Id).ToList();

            //查询角色权限关系表中的角色信息
            var role_permission = rolePermissonRepository.GetAll().Result.Where(m => m.RoleId == dto.Id).ToList();

            //开始事务
            using (var tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //判断角色是否存在
                    if (role == null)
                    {
                        return new ResultDTO<string>
                        {
                            Code = Enum.ResultStatusCode.ENTITYNULL,
                            Message = "删除失败",
                            Data = "角色不存在"
                        };
                    }

                    //判断，删除 用户角色关系表
                    if (user_role != null)
                    {
                        await roleuserRepository.DeleteBatch(user_role);
                        await unitOfWork.SaveChanges();

                    }

                    //判断，删除 角色权限关系表
                    if (role_permission != null)
                    {
                        await rolePermissonRepository.DeleteBatch(role_permission);
                        await unitOfWork.SaveChanges();
                    }

                    //删除 角色表
                    await roleRepository.Delete(role);


                    //提交数据
                    await unitOfWork.SaveChanges();

                    //提交事务
                    tran.Commit();

                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.SUCCESS,
                        Message = "删除成功",
                        Data = "角色：" + role.Name + "已删除"
                    };
                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Rollback();

                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.SUCCESS,
                        Message = "删除失败",
                        Data = "角色：" + role.Name + "未删除"
                    };
                }
            }
        }

        /// <summary>
        /// 角色的批量真删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> RoleDelAll(string idList)
        {
            string[] ids=idList.Split(',');
 
            //实例化一个role类型的集合
            List<RoleInfo> rolelist = new List<RoleInfo>();

            //循环判断选中角色是否被删除
            foreach (var id in ids)
            {
                var list = (await roleRepository.GetAll()).Where(m => m.Id == Convert.ToInt32(id) && m.IsDeleted == false).FirstOrDefault();
                if (list == default)
                {
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.ENTITYNULL,
                        Message = "存在未查找到的角色",
                        Data = "角色编号：" + id + "的角色不存在"
                    };
                }
                rolelist.Add(list);
            }          

            //开启事务
            using (var tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //查询用户角色关系表中的角色信息
                    foreach (var id in ids)
                    {
                        //查询用户角色关系表中的角色信息
                        var user_role = roleuserRepository.GetAll().Result.Where(m => m.RoleId == Convert.ToInt32(id)).ToList();
                        //判断，删除 用户角色关系表
                        if (user_role != null)
                        {
                            await roleuserRepository.DeleteBatch(user_role);
                            await unitOfWork.SaveChanges();
                        }

                        //查询角色权限关系表中的角色信息
                        var role_permission = rolePermissonRepository.GetAll().Result.Where(m => m.RoleId == Convert.ToInt32(id)).ToList();
                        //判断，删除 角色权限关系表
                        if (role_permission != null)
                        {
                            await rolePermissonRepository.DeleteBatch(role_permission);
                            await unitOfWork.SaveChanges();
                        }
                    }

                    //批量删除
                    await roleRepository.DeleteBatch(rolelist);

                    //提交数据
                    await unitOfWork.SaveChanges();

                    //提交事务
                    tran.Commit();

                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.SUCCESS,
                        Message = "删除成功",
                        Data = "角色已批量删除"
                    };
                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Rollback();
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.HANDLEFAIL,
                        Message = "删除失败",
                        Data = null
                    };
                }
            }
        }

        /// <summary>
        /// 单个角色的逻辑删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> RoleSoftDel(int id)
        {
            //选择逻辑删除的角色
            var role = roleRepository.GetAll().Result.Where(m => m.Id == id).FirstOrDefault();

            try
            {
                //判断角色是否存在
                if (role == null)
                {
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.ENTITYNULL,
                        Message = "删除失败",
                        Data = "角色不存在"
                    };
                }

                //修改 角色表
                role.IsDeleted = true;
                await roleRepository.Update(role);

                //提交数据
                await unitOfWork.SaveChanges();

                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.SUCCESS,
                    Message = "删除成功",
                    Data = "角色：" + role.Name + "已删除"
                };
            }
            catch (Exception)
            {
                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.SUCCESS,
                    Message = "删除失败",
                    Data = "角色：" + role.Name + "未删除"
                };
            }
        }

        /// <summary>
        /// 角色的批量逻辑删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> RoleSoftDelAll(string idList)
        {
            string[] ids= idList.Split(',');

            var listt = await roleRepository.GetAll();
            
            //循环判断选中角色是否被删除
            foreach (var id in ids)
            {

                var list = listt.Where(m => m.Id == Convert.ToInt32(id) && m.IsDeleted == false).FirstOrDefault();
                if (list == default)
                {
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.ENTITYNULL,
                        Message = "存在未查找到的角色",
                        Data = "角色编号：" + id + "的角色不存在"
                    };
                }
            }

            //开启事务
            using(var tran=unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //批量修改
                    foreach (var id in ids)
                    {
                        var role = (await roleRepository.GetAll()).Where(m => m.Id == Convert.ToInt32(id)).FirstOrDefault();
                        role.IsDeleted = true;
                        role.UpdateTime = DateTime.Now;
                        await roleRepository.Update(role);
                    }

                    //提交数据
                    await unitOfWork.SaveChanges();

                    //提交事务
                    tran.Commit();

                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.SUCCESS,
                        Message = "删除成功",
                        Data = "角色已批量删除"
                    };
                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Rollback();
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.HANDLEFAIL,
                        Message = "删除失败",
                        Data = null
                    };
                }
            }
        }

        /// <summary>
        /// 角色分配权限
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> RolePermissionAllot(PermissionAllotDTO dto)
        {
            //开始事务
            using (var tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //删除角色的所有旧权限
                    var delData = (await rolePermissonRepository.GetAll()).Where(m => m.RoleId == dto.id).ToList();
                    await rolePermissonRepository.DeleteBatch(delData);

                    //定义RolePermission（角色权限表）类型
                    List<RolePermissions> list = new List<RolePermissions>();

                    //循环添加权限
                    foreach (var item in dto.permissionId)
                    {
                        list.Add(new RolePermissions { RoleId = dto.id, PermissionId = item });
                    }

                    //批量添加角色的权限
                    await rolePermissonRepository.InsertBatch(list);

                    //提交数据
                    int h = await unitOfWork.SaveChanges();

                    //提交事务
                    tran.Commit();

                    //返回值
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.SUCCESS,
                        Message = "操作成功",
                        Data = ""
                    };

                }
                catch (Exception ex)
                {
                    //回滚事务
                    tran.Rollback();
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.HANDLEFAIL,
                        Message = "操作失败",
                        Data = ex.Message
                    };
                }
            }
        }






    }
}
